/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.mybatis.ext.sql.support;

import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/** 批量工具类 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class BatchUtils {

  /**
   * 批量执行
   *
   * @param items 项目集合
   * @param batchSize 批量大小
   * @param itemHandler 项目处理器
   * @param batchHandler 批量处理器
   * @param <T> 项目类型
   */
  public static <T> void batchExecute(
      Collection<T> items, int batchSize, Consumer<T> itemHandler, IntConsumer batchHandler) {
    int size = items.size();
    int indexLimit = Math.min(batchSize, size);
    int i = 1;
    int batchCount = 1;
    for (T item : items) {
      itemHandler.accept(item);
      if (i == indexLimit) {
        batchHandler.accept(batchCount++);
        indexLimit = Math.min(indexLimit + batchSize, size);
      }
      i++;
    }
  }
}
